package com.zrrd.comparator;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * @author WanJl
 * @version 1.0
 * @title ComparatorTreeSetTest
 * @description
 *  在将元素放入TreeSet集合的时候，使用比较器对象Comparator作为参数定义顺序
 *
 * @create 2024/4/21
 */
public class ComparatorTreeSetTest {
    public static void main(String[] args) {
        TreeSet<Teacher> set=new TreeSet<>(new Comparator<Teacher>() {
            @Override
            public int compare(Teacher o1, Teacher o2) {
                //o1 表示现在要存入到集合中的元素
                //o2 表示已经存入大到集合中的元素

                //主要条件-根据年龄大小排序
                int r=o1.getAge()-o2.getAge();
                //次要条件-年龄相同，按照姓名的字母顺序排序
                if(r==0){
                    return o1.getName().compareTo(o2.getName());
                }
                return r;
            }
        });

        Teacher t1=new Teacher("张三",25);
        Teacher t2=new Teacher("王三",15);
        Teacher t3=new Teacher("李三",15);
        Teacher t4=new Teacher("侯三",66);
        Teacher t5=new Teacher("刘三",35);
        Teacher t6=new Teacher("马三",74);

        set.add(t1);
        set.add(t2);
        set.add(t3);
        set.add(t4);
        set.add(t5);
        set.add(t6);

        set.forEach(System.out::println);
    }
}
